package com.myzxapp.imusic;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;

import android.view.Window;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.media.app.NotificationCompat.MediaStyle;

import com.myzxapp.Utils.AssetUtils;
import com.myzxapp.imusic.databinding.ActivityMainBinding;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private String notificationChannelId;
    private ActivityMainBinding binding;
    private NotificationCompat.Builder notificationBuilder;
    private MediaSessionCompat mediaSession;
    private NotificationManager notificationManager;
    private MediaPlayer mediaPlayer;
    private int currentTrackIndex = 0; // 从0开始
    private List<String> soundFileList;
    private String currentTrackName;
    private int duration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        soundFileList = AssetUtils.getFilesInAssets(this, "Sounds/");
        currentTrackName = extractTrackName(getTrackPath(currentTrackIndex));

        notificationChannelId = createNotificationChannel("08", "iLikeMusic", NotificationManager.IMPORTANCE_HIGH);
        notificationBuilder = createNotificationBuilder();

        mediaSession = new MediaSessionCompat(this, "iLikeMusic");
        mediaSession.setCallback(createMediaSessionCallback());
        mediaSession.setActive(true);
        notificationBuilder.setStyle(new MediaStyle().setMediaSession(mediaSession.getSessionToken()));

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(8, notificationBuilder.build());

        playTrack(currentTrackIndex);
        configureWindow(getWindow());
        updatePlaybackState(PlaybackStateCompat.STATE_PLAYING,0);
    }

    private void configureWindow(Window window) {
        try {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0);
            getSupportActionBar().hide();
            window.getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private MediaMetadataCompat createMediaMetadata(String title, String artist, int duration) {
        return new MediaMetadataCompat.Builder()
                .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
                .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, artist)
                .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration)
                .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "iLikeMusic")
                .build();
    }

    private String createNotificationChannel(String channelID, String channelName, int importanceLevel) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(channelID, channelName, importanceLevel);
        manager.createNotificationChannel(channel);
        return channelID;
    }

    private NotificationCompat.Builder createNotificationBuilder() {
        return new NotificationCompat.Builder(this, notificationChannelId)
                .setSmallIcon(R.drawable.icon)
                .setContentTitle("iLikeMusic")
                .setContentText("my song")
                .setOngoing(true)
                .setAutoCancel(false)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE);
    }

    private MediaSessionCompat.Callback createMediaSessionCallback() {
        return new MediaSessionCompat.Callback() {
            @Override
            public void onSeekTo(long pos) {
                if (mediaPlayer.getCurrentPosition() != duration) {
                   upMusicProgress(pos);
                }
            }

            @Override
            public void onPlay() {
                startMusicPlayback();
            }

            @Override
            public void onPause() {
                pauseMusicPlayback();
            }

            @Override
            public void onSkipToNext() {
                skipToNextTrack();
            }

            @Override
            public void onSkipToPrevious() {
                skipToPreviousTrack();
            }
        };
    }

    private void startMusicPlayback() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            updatePlaybackState(PlaybackStateCompat.STATE_PLAYING,mediaPlayer.getCurrentPosition());
        }
    }

    private void pauseMusicPlayback() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            updatePlaybackState(PlaybackStateCompat.STATE_PAUSED,mediaPlayer.getCurrentPosition());
        }
    }

    private void skipToNextTrack() {
        changeTrack(1);
    }

    private void skipToPreviousTrack() {
        changeTrack(-1);
    }

    private void changeTrack(int direction) {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
        }
        currentTrackIndex += direction;
        if (currentTrackIndex < 0) currentTrackIndex = 0;
        if (currentTrackIndex >= soundFileList.size()) currentTrackIndex = soundFileList.size() - 1;
        upMusicProgress(0);
        playTrack(currentTrackIndex);
    }

    private void updatePlaybackState(int state,int progress) {
        if (mediaPlayer != null) {
            PlaybackStateCompat.Builder playbackStateBuilder =
                    new PlaybackStateCompat.Builder()
                            .setActions(
                                    PlaybackStateCompat.ACTION_PLAY
                                            | PlaybackStateCompat.ACTION_PAUSE
                                            | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
                                            | PlaybackStateCompat.ACTION_SEEK_TO)
                            .setState(state, progress, 1, SystemClock.elapsedRealtime());
            mediaSession.setPlaybackState(playbackStateBuilder.build());
        }
    }

    private void playTrack(int trackIndex) {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release(); // 释放之前的 MediaPlayer
            }
            AssetManager assetManager = getAssets();
            AssetFileDescriptor assetFileDescriptor = assetManager.openFd(getTrackPath(trackIndex));
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(
                    assetFileDescriptor.getFileDescriptor(),
                    assetFileDescriptor.getStartOffset(),
                    assetFileDescriptor.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
            duration = mediaPlayer.getDuration();
            updateNotification(trackIndex, duration);
            mediaPlayer.setOnCompletionListener(mp -> skipToNextTrack());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateNotification(int trackIndex, int duration) {
        currentTrackName = extractTrackName(soundFileList.get(trackIndex));
        MediaMetadataCompat mediaMetadata = createMediaMetadata(currentTrackName, getTrackPath(currentTrackIndex), duration);
        mediaSession.setMetadata(mediaMetadata);
        notificationManager.notify(8, notificationBuilder.build());
    }
    
    private void upMusicProgress(long currentPosition) {
        mediaPlayer.seekTo((int) currentPosition);
        currentTrackName = extractTrackName(soundFileList.get(currentTrackIndex));
        updatePlaybackState(PlaybackStateCompat.STATE_PLAYING,mediaPlayer.getCurrentPosition());
    }

    private String extractTrackName(String filePath) {
        int index = filePath.indexOf('/');
        return (index != -1) ? filePath.substring(index + 1) : "";
    } // 避免重复使用

    private String getTrackPath(int trackIndex) {
        return soundFileList.get(trackIndex);
    } // 避免重复使用

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release(); // 释放 MediaPlayer
            mediaPlayer = null; // 避免空值引用
        }
        notificationManager.cancel(8); // 取消通知
        binding = null;
    }
}
